﻿#include "StudyQtWebEngine.h"
#include "MFWebChannelBridge.h"

StudyQtWebEngine::StudyQtWebEngine(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    QVBoxLayout* pLayoutMain = new QVBoxLayout(ui.centralWidget);
    ui.centralWidget->setLayout(pLayoutMain);
    pLayoutMain->setContentsMargins(0, 30, 0, 0);
    {
        m_view = new QWebEngineView(ui.centralWidget);
        pLayoutMain->addWidget(m_view);
        {
			QWebChannel* channel = new QWebChannel(m_view);
            MFWebChannelBridge* pBridge = new MFWebChannelBridge(channel);
			channel->registerObject("webChannelBridge", pBridge);
            m_view->page()->setWebChannel(channel);
        }

		QWebEngineView* view1 = new QWebEngineView(m_view);
		pLayoutMain->addWidget(view1);
        m_view->page()->setDevToolsPage(view1->page());
    }

    connect(ui.btnRunJs3, &QPushButton::clicked, this, &StudyQtWebEngine::TestBtnRunJs3Clicked);
    connect(ui.btnRunJs4, &QPushButton::clicked, this, &StudyQtWebEngine::TestBtnRunJs4Clicked);


    m_view->page()->profile()->setHttpCacheType(QWebEngineProfile::NoCache);
    m_view->load(QUrl::fromLocalFile(QCoreApplication::applicationDirPath()+"/index.html"));
}

void StudyQtWebEngine::TestBtnRunJs3Clicked()
{
	m_view->page()->runJavaScript("onShowJsAlert3()");

    qDebug() << TR("运行Js是异步的");
}

void StudyQtWebEngine::TestBtnRunJs4Clicked()
{
    QJsonObject jsonObj;
    jsonObj.insert("msgId", "44");
    jsonObj.insert("msg", TR("这是Js的弹框 4"));

    QString strMsg = QJsonDocument(jsonObj).toJson(QJsonDocument::Compact);
    QString strJs = QString("onShowJsAlert4(%1)").arg(strMsg);
    QWebEngineCallback<const QVariant&> resultCallback = [](const QVariant& v)
    {
        qDebug() << TR("4 Js的返回值是：") << v.toJsonObject();
    };
    m_view->page()->runJavaScript(strJs, resultCallback);

    qDebug() << TR("运行Js是异步的，Qt无法同步获取Js函数运行结果, 要知道运行结果，需要回调函数");
}

